var WEB_SOCKET_UTILS = {
    ws: null,
    userId: null,
    generateUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random() * 16 | 0,
                v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    },
    initWebSocket(url, userId) {
        if ("WebSocket" in window) {
            if (this.ws != null) {
                this.ws.close();
                this.ws = null;
            }
            if (!userId) {
                if (localStorage.getItem(window.location.hostname + '_userId')) {
                    userId = localStorage.getItem(window.location.hostname + '_userId');
                } else {
                    userId = this.generateUUID();
                }
            }
            this.userId = userId;
            localStorage.setItem(window.location.hostname + '_userId', this.userId);
            this.ws = new WebSocket(`${url}${userId}`);
            this.ws.onopen = () => {
                console.log('WebSocket连接已建立');
                this.open();
            };
            this.ws.onmessage = (evt) => {
                console.log('WebSocket接收到消息：', evt.data);
                this.message(evt);
            };
            this.ws.onclose = () => {
                console.log('WebSocket连接已断开');
                this.close();
            };
            return this.ws;
        } else {
            console.log('您的浏览器不支持 WebSocket!');
        }
    },
    open() {
    },
    message(evt) {
    },
    close() {
    },
    send(msg){
        if (this.ws && this.ws.readyState === 1) {
            this.ws.send(msg);
        }
    }
}